/*
 * @Author: ayun chengyunwu@jiatui.com
 * @Date: 2023-07-11 18:07:47
 * @LastEditors: ayun chengyunwu@jiatui.com
 * @LastEditTime: 2023-07-28 15:03:29
 * @FilePath: /ift-economy-network-h5/src/pages/InvestmentScheduling/Home/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import Styles from "./index.module.scss";
import { useNavigate } from "react-router-dom";
import { Button, Checkbox, Form, Input, Toast } from "antd-mobile";
import { login, loginImage } from "@/service/InvestmentScheduling";
import MD5 from "js-md5";
import forge from "node-forge";
import Cookies from "js-cookie";
import { useEffect, useState } from "react";
import { getRandomStr } from "@/utils/commonUtils";
import loginTest from "@/common/loginTest"

const SSO_PUBLIC_KEY =
  "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp30wda2keZWAyLc02szbDbKNuAxsYei1STGlIMsODMqip/+HB5yh3KLi3TAVLvGdd8Hm8p//wQlnyS9h3gpaiFBgeLwn6PJvz4wrbPxxV7bwxcJupZrrCWJEOuJQvfs4Yogafs4vpctCcjdKXoNr6Ak7eaKOqkUcjOxEcVeudmcn1ryqCe5B1nDtOeuP6OdMkJNFFwdbjQH5D/zQLfqRtMQCAn4pWork0kleNus3H+g/nx5kxwi/kRIq2OvxkTZ1mdwxc7WKoWDvU9sx/wcPa4hbge4Sm+zzHdrp+OMhq7NP0IEEdtJpl8+YjPPUTw6BBPmWPInx4HIWNI09mXeNJQIDAQAB\n-----END PUBLIC KEY-----";
const publicKey = forge.pki.publicKeyFromPem(SSO_PUBLIC_KEY);

const index = () => {
  
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [imageSrc, setImageSrc] = useState<any>('')
  const [verificationId, setVerificationId] = useState<any>('')

  const loginImages = async() => {
    const res:any = await loginImage()
    setImageSrc(res?.data?.data?.image)
    setVerificationId(res?.data?.data?.verificationId)
  }

  useEffect(() => {
    loginImages()
  },[])

  // 登录事件
  const handleLogin = async (values: any) => {
    Cookies.remove('pai_token')
    Cookies.remove('user_deptName')
    const { username, password, code } = values;

    // if (username !== 'admin' || password !== '123456')
    //   return Toast.show({ content: '账号或密码错误' })
    const str = getRandomStr();

    const result = {
      userName: username,
      pwd: password,
      timestamp: Date.now(),
    };
    const appCode = import.meta.env.VITE_APPCODE;
    const secret = import.meta.env.VITE_SECRET;
    const loginParams = {
      sign:
        MD5(
          appCode + result.userName + result.pwd + result.timestamp + secret
        ) + str,
      appCode,
      encryptedJson: "",
      verificationId: verificationId,
      verificationCode: code
    };

    loginParams.encryptedJson = window.btoa(
      publicKey.encrypt(
        JSON.stringify({
          userName: result.userName + str,
          pwd: result.pwd + str,
          timestamp: result.timestamp,
        }),
        "RSA-OAEP",
        {
          md: forge.md.sha256.create(),
          mgf1: {
            md: forge.md.sha1.create(),
          },
        }
      )
    );

    const res = await login(loginParams)
    const data = res.data
    if(loginTest.loginTestSwitch){
      Cookies.set("pai_token",loginTest.pai_token)
      Cookies.set("pai_refresh_token",loginTest.pai_refresh_token)
    }else{
      if (!data.data?.userToken) {
        // 登陆异常需要重新刷新图片验证码
        loginImages()
        return Toast.show(data.msg.message)
      }
      Cookies.set("pai_token", data.data.userToken)
      Cookies.set("pai_refresh_token", data.data.refreshToken)
    }
    navigate("/investment-scheduling-home", { replace: true });
  };

  return (
    <div className={`${Styles.container}`}>
      <div
        className={`bg_ffffff base-content-view m_l_r_12 ${Styles.login_window}`}
      >
        <span className={`fontsize_21 color_333 fw_600`}>登录</span>
        <Form form={form} onFinish={handleLogin} className={`${Styles.form}`}>
          <Form.Item
            name="username"
            rules={[
              {
                required: true,
                message: "账号不能为空",
              },
            ]}
          >
            <Input
              placeholder="账号"
              clearable
              className={`${Styles.mt_18} ${Styles.br_6} ${Styles.ipt}`}
            />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[
              {
                required: true,
                message: "密码不能为空",
              },
            ]}
          >
            <Input
              placeholder="密码"
              clearable
              type="password"
              className={`${Styles.br_6} ${Styles.ipt}`}
            />
          </Form.Item>
          <div style={{display: 'flex', justifyContent: 'space-between'}}>
            <div style={{width: '50%'}}>
              <Form.Item
                name="code"
                rules={[
                  {
                    required: true,
                    message: "验证码不能为空",
                  },
                ]}
              >
                <Input
                  placeholder="验证码"
                  clearable
                  type="code"
                  className={`${Styles.br_6} ${Styles.ipt}`}
                />
              </Form.Item>
            </div>
            <img onClick={() =>loginImages()} style={{height: '45px', marginTop: '10px'}} src={`data:image/png;base64,${imageSrc}`} />
          </div>
          <div className={`d_between_center ${Styles.mt_20}`}>
            {/* <Checkbox
              style={{
                "--font-size": "16px",
                "--gap": "6px",
              }}
            >
              <span className={"fontsize_16 color_333"}>自动登录</span>
            </Checkbox> */}
            {/* <span className={`fontsize_16 ${Styles.color_0f9de9}`}>
              忘记密码
            </span> */}
          </div>
          <Button
            block
            type="submit"
            color="primary"
            size="large"
            className={`${Styles.mt_40} ${Styles.bg_0f9de9} ${Styles.btn}`}
          >
            登录
          </Button>
        </Form>
      </div>
    </div>
  );
};

export default index;
